package net.lanelife.casino.caipiao.service;

import java.util.List;

import javax.persistence.LockModeType;

import net.lanelife.casino.caipiao.entity.UserLayer;
import net.lanelife.casino.caipiao.entity.UserLayer_;
import net.lanelife.casino.caipiao.exception.DefaultUserLayerCanNotDeleteException;
import net.lanelife.casino.caipiao.repository.api.IUserLayerRepository;
import net.lanelife.casino.caipiao.service.api.IUserLayerService;
import net.lanelife.casino.common.aop.annotation.RetriableTransaction;
import net.lanelife.casino.common.dto.support.IGenericDTO;
import net.lanelife.casino.common.repository.support.GenericRepository;
import net.lanelife.casino.common.service.support.GenericService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserLayerService extends GenericService<UserLayer, Integer> implements IUserLayerService {

	@Autowired
	private IUserLayerRepository repository;
	
	public UserLayerService() {
		super(UserLayer.class);
	}
	
	@Override
	protected GenericRepository<UserLayer, Integer> getRepository() {
		return repository;
	}
	
	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public <DTO extends IGenericDTO<Integer>> List<DTO> findAll(Class<DTO> dtoClass) throws Exception {
		return findAll(dtoClass, new Sort(Direction.ASC, UserLayer_.deep.getName())); // 按序号排序
	}

	@Override
	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public UserLayer findDefault() {
		return repository.findByIsDefault(Boolean.TRUE);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delete(Integer id) throws Exception {
		UserLayer layer = repository.findOne(id, LockModeType.PESSIMISTIC_WRITE);
		if (layer.getIsDefault()) {
			throw DefaultUserLayerCanNotDeleteException.ERROR;
		}
		repository.migrateUsers(layer.getId(), repository.findByIsDefault(Boolean.TRUE).getId()); //转移用户到默认分层
		super.delete(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void countUsers() {
		repository.countUsers();
	}

	@Override
	@RetriableTransaction
	@Transactional(rollbackFor = Exception.class)
	public void setAsDefault(Integer id) {
		repository.findByIsDefault(Boolean.TRUE).setIsDefault(Boolean.FALSE);
		repository.findOne(id).setIsDefault(Boolean.TRUE);
	}
	
	


}
